import Vue from 'vue'
import Router from 'vue-router'
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
import store from '@/store'

import page401 from '@/views/401'
import page404 from '@/views/404'
import login from '@/views/login'
import layout from '@/views/Layout'
import dashboard from '@/views/Dashboard'
import table from '@/views/table'
import tree from '@/views/tree'
import documentation from '@/views/documentation'
import permission from '@/views/permission'
import svgIcons from '@/views/svg-icons'
import tinymce from '@/views/components/tinymceView'
import markdown from '@/views/components/markdownView'
import jsonEditorView from '@/views/components/jsonEditorView'

Vue.use(Router)
export const constRouters = [
  // 401状态码处理
  { name: '401', path: '/401', component: page401, meta: {hidden: true} },
  // 404状态码处理
  { name: '404', path: '/404', component: page404, meta: {hidden: true} },
  // 登录
  { name: 'login', path: '/login', component: login, meta: {hidden: true} },
  //仪表盘
  {
    name: 'dashboard',
    path: '/',
    redirect: '/dashboard',
    component: layout,
    children:[
      {
        name: dashboard.name,
        path: 'dashboard',
        component: dashboard,
        meta: {title: '首页', icon: 'dashboard', noCache: false},
      }
    ]
  },
  //文档
  {
    name: 'documentation',
    path: '/documentation/',
    redirect: '/documentation/index',
    component: layout,
    children:[
      {
        name: documentation.name,
        path:'index',
        component: documentation,
        meta: {title: '文档', icon: 'documentation'}
      }
    ]
  }]
export const asyncRouters = [
  {
    //示例
    name: 'permission',
    path: '/permission/',
    redirect: '/permission/index',
    component: layout,
    children:[
      {
        name: permission.name,
        path: 'index',
        component: permission,
        meta: {title: '权限', icon: 'lock', roles:['admin']}
      }
    ]
  },
  {
    path: '/svg-icons/',
    redirect: '/svg-icons/index',
    component: layout,
    children:[
      {
        name: svgIcons.name,
        path: 'index',
        component: svgIcons,
        meta: {title: '图标', icon: 'icon'}
      }
    ]
  },
  {
    //示例
    name: 'components',
    path: '/components/',
    redirect: '/components/tinymce',
    component: layout,
    meta: {title: '组件', icon: 'component'},
    children:[
      {
        //表格
        name: tinymce.name,
        path: 'tinymce',
        component: tinymce,
        meta: {title: '富文本编辑器', noCache: false}
      },
      {
        name: markdown.name,
        path: 'markdown',
        component: markdown,
        meta: {title: 'Markdown'}
      },
      {
        name: jsonEditorView.name,
        path: 'jsonEditorView',
        component: jsonEditorView,
        meta: {title: 'JSONEditor'}
      }
    ]
  },
  //其它不匹配路由处理
  {
    name: 'unmatched',
    path: '*',
    redirect: '/404',
    meta:{hidden: true}
  }
]

const router = new Router({
  routes: constRouters
})

//检查访问权限

function hasPermission(roles, router) {
  return roles.some(role=>{
    return router.meta === undefined || router.meta.roles === undefined || router.meta.roles.indexOf(role) > -1;
  })
}

let whiteList = ['/login', '/404']
router.beforeEach((to, from, next)=>{
  nprogress.start()

  if(to.path === "/login" && store.getters.token){
    //访问白名单中的login，如果有token则转向首页
    next({path: '/'})
  }else if(whiteList.indexOf(to.path) != -1){
    //访问白名单中的其它页面，直接访问
    next()
  } else if(store.getters.token) {
    //访问非白名单页面，但有token
    if (store.getters.roles.length === 0) {
      //验证token，拉取用户信息
      store.dispatch('getUserInfo')
        .then(({roles}) => {
          //拉取用户信息成功，根据角色添加动态路由
          store.dispatch("generateRoutes", roles)
            .then(()=>{
              router.addRoutes(store.getters.addRoutes)
              //访问页面
              next({ ...to, replace: true }) // hack方法 确保addRoutes已完成 ,replace: true so the navigation will not leave a history record
            })
            .catch(error=>{
              console.log(`router.beforeEach>generateRoutes>${error}`)
              next()
            })
        })
        .catch(error => {
          console.log(`router.beforeEach>getUserInfo>${error}`)
          //拉取用户信息失败，重新登录
          store.dispatch('logout')
            .then(()=>{
              next({path: '/login'})
            })
            .catch((error)=>{
              console.log(`router.beforeEach>getUserInfo>logout>${error}`)
              next({path: '/login'})
            })
        })
    } else {
      //成功拉取用户信息，动态验证权限
      if(hasPermission(store.getters.roles, to)){
        //验证成功，直接访问该页面
        next()
      } else {
        //没有权限
        next({path: '/401', query:{noGoBack: false}})
      }
    }
  } else {
    //访问非白名单页面，无token
    next({path: '/login'})
  }

  nprogress.done()
})

export default router
